package cn.zhz.dao;

import cn.zhz.pojo.Dept;
import cn.zhz.pojo.Emp;
import cn.zhz.pojo.EmpCondition;
import org.hibernate.Query;

import java.io.Serializable;
import java.util.Iterator;
import java.util.List;

public class EmpDao extends BaseDao{

    public Iterator<Emp> findIterae(){
        Iterator<Emp> iterator=null;
        String hql = "from Emp";
        Query query = super.currentSession().createQuery(hql);
        iterator = query.iterate();
        return iterator;
    }

    public List<Emp> findByConditions(Emp conditions) {
        String hql = "from Emp where job = :job and sal > :sal";
        Query query = currentSession().createQuery(hql);
        query.setProperties(conditions); // 根据参数名获取相应的属性值进行赋值
        return query.list();
    }
    public List<Emp> findByInvisibleJoin(String deptName){
        String hql = "from Emp e  where e.dept.deptName=?";
        return currentSession().createQuery(hql).setString(0,deptName).list();
    }

    public List<Object[]> findGroupBy(){
        String hql = "select e.job, count(e) from Emp e group by e.job";
        return currentSession().createQuery(hql).list();
    }

    public List<Emp> findByConditions(Object[] conditions){
        String hql = "from Emp where job = ? and sal > ?";
        Query query = currentSession().createQuery(hql);
        if(conditions != null && conditions.length>0){
            for (int i = 0;i<conditions.length;++i){
                query.setParameter(i,conditions[i]);
            }
        }
        return query.list();
    }

    public List<Emp> findByConditions2(Emp conditions){
        String hql = "from Emp where job = :job and sal >:salary";
        Query query = currentSession().createQuery(hql);
        query.setProperties(conditions);
        return query.list();
    }
    public List<Emp> findByConditions(String hql,EmpCondition empCondition){
        return currentSession().createQuery(hql).setProperties(empCondition).list();
    }

    public Long obtainTheRowCount(Double sal){
        String hql = "select count(id) from Emp where sal >= :sal";
        return (Long)currentSession().createQuery(hql).setDouble("sal",sal).uniqueResult();
    }

    public List<Emp> findByPage(int pageNo,int pageSize){
        return currentSession().createQuery("from Emp order by id")
                .setFirstResult((pageNo-1)*pageSize)
                .setMaxResults(pageSize).list();
    }
    public void save(Emp emp){
        this.currentSession().save(emp);
    }
    public List<Emp> findByDept(Dept dept){
        String hql = "from Emp where dept = ?";
        return this.currentSession().createQuery(hql).setParameter(0,dept).list();
    }
    public List<Emp> findAll(){
        return this.currentSession().createQuery("from Emp").list();
    }

    public Emp load(Serializable empNo){
        return (Emp)this.currentSession().load(Emp.class,empNo);
    }
}
